package com.epam.springtest.dao;

import com.epam.springtest.domain.User;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mikalai Kisel
 */
public class UserDaoImpl implements UserDao {

    private DataSource datasource;

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void setDatasource(DataSource datasource) {
        this.datasource = datasource;
        this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(datasource);
    }

    @Override
    public User findUserByEmail(String email) {
        String sql = "select * from app_user where email = :userEmail";
        SqlParameterSource namedParameters =
                new MapSqlParameterSource("userEmail", email);
        List<User> users = namedParameterJdbcTemplate.query(sql, namedParameters, new UserMapper());
        if (users.size()==1)
            return users.get(0);
        else
            return null;
    }

    @Override
    public String findByEmail(String email) {
        String sql =  "select name from app_user where email = :userEmail";
        SqlParameterSource namedParameters =
                new MapSqlParameterSource("userEmail", email);
        return namedParameterJdbcTemplate.queryForObject(sql,
                namedParameters, String.class);
    }

    @Override
    public void insert(User user) {
        String sql = "insert into app_user (email, name, password) values (:email, :name, :password)";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("email", user.getEmail());
        params.put("name", user.getName());
        params.put("password", user.getPassword());
        namedParameterJdbcTemplate.update(sql, params);
    }
}
